Files
MY_COMPILER/frontend/ast/exp/PrimaryExp.java
2025-12-12 20:14:00 +08:00

59 lines
1.8 KiB
Java
Executable File

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 error.Errors;
import error.Error;
import error.ErrorType;
public class PrimaryExp extends Node {
public PrimaryExp(TokenStream ts) {
super(SyntaxType.PRIMARY_EXP, ts);
}
public void parse(Errors errors) {
if (getCurrToken().getType() == TokenType.LPARENT) {
addChild(new TokenNode(ts)); // lparent
Exp exp = new Exp(this.ts);
exp.parse(errors);
addChild(exp);
if (getCurrToken().getType() == TokenType.RPARENT) {
addChild(new TokenNode(ts)); // rparent
} else {
errors.addError(new Error(this.ts.peek(-1).getLine(), ErrorType.j));
}
} else if (getCurrToken().getType() == TokenType.IDENFR) {
LVal lval = new LVal(this.ts);
lval.parse(errors);
addChild(lval);
} else {
NumberExp num = new NumberExp(this.ts);
num.parse(errors);
addChild(num);
}
}
public int getType() {
if (getChild(0) instanceof TokenNode) {
return ((Exp) getChild(1)).getType();
} else if (getChild(0) instanceof LVal) {
return ((LVal) getChild(0)).getType();
} else {
return 0;
}
}
public int getValue() {
if (getChild(0) instanceof TokenNode) {
return ((Exp) getChild(1)).getValue();
} else if (getChild(0) instanceof LVal) {
return ((LVal) getChild(0)).getValue();
} else {
return ((NumberExp) getChild(0)).getValue();
}
}
}