74 lines
2.1 KiB
Java
74 lines
2.1 KiB
Java
package frontend.ast.exp;
|
|
|
|
import frontend.ast.Node;
|
|
import frontend.ast.NodeStack;
|
|
import frontend.ast.SyntaxType;
|
|
import frontend.lexer.TokenStream;
|
|
import frontend.lexer.TokenType;
|
|
import frontend.ast.token.TokenNode;
|
|
import midend.symbol.SymbolManager;
|
|
import error.Errors;
|
|
|
|
public class AddExp extends Node {
|
|
public AddExp(TokenStream ts) {
|
|
super(SyntaxType.ADD_EXP, ts);
|
|
}
|
|
|
|
public void parse(Errors errors) {
|
|
NodeStack stack = new NodeStack();
|
|
while (true) {
|
|
MulExp mep = new MulExp(this.ts);
|
|
mep.parse(errors);
|
|
stack.push(mep);
|
|
if (isAddOp()) {
|
|
stack.push(new TokenNode(ts)); // addop
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
if (stack.size() == 1) {
|
|
this.addChild((MulExp) stack.pop());
|
|
} else {
|
|
AddExp temp = this;
|
|
while (stack.size() > 1) {
|
|
AddExp ae = new AddExp(this.ts);
|
|
MulExp mep = (MulExp) stack.pop();
|
|
TokenNode op = (TokenNode) stack.pop();
|
|
temp.addChild(ae);
|
|
temp.addChild(op);
|
|
temp.addChild(mep);
|
|
temp = ae;
|
|
}
|
|
temp.addChild((MulExp) stack.pop());
|
|
}
|
|
}
|
|
|
|
public boolean isAddOp() {
|
|
TokenType t = getCurrToken().getType();
|
|
return t == TokenType.PLUS || t == TokenType.MINU;
|
|
}
|
|
|
|
public int getType() {
|
|
if (getChildren().size() == 1) {
|
|
return ((MulExp) getChild(0)).getType();
|
|
} else {
|
|
return ((AddExp) getChild(0)).getType()
|
|
| ((MulExp) getChild(2)).getType();
|
|
}
|
|
}
|
|
|
|
public int getValue() {
|
|
if (getChild(0) instanceof MulExp) {
|
|
return ((MulExp) getChild(0)).getValue();
|
|
} else {
|
|
int left = ((AddExp) getChild(0)).getValue();
|
|
int right = ((MulExp) getChild(2)).getValue();
|
|
if (((TokenNode) getChild(1)).getType() == TokenType.PLUS) {
|
|
return left + right;
|
|
} else {
|
|
return left - right;
|
|
}
|
|
}
|
|
}
|
|
}
|