Files
MY_COMPILER/frontend/ast/exp/LVal.java
2025-12-10 17:58:17 +08:00

60 lines
1.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package frontend.ast.exp;
import frontend.ast.Node;
import frontend.ast.SyntaxType;
import frontend.ast.token.TokenNode;
import frontend.lexer.TokenStream;
import frontend.lexer.TokenType;
import midend.symbol.SymbolManager;
import midend.symbol.Symbol;
import midend.symbol.ArraySymbol;
import error.Errors;
import error.Error;
import error.ErrorType;
public class LVal extends Node {
public LVal(TokenStream ts) {
super(SyntaxType.LVAL_EXP, ts);
}
public void parse(Errors errors) {
addChild(new TokenNode(this.ts)); // idenfr
if (getCurrToken().getType() == TokenType.LBRACK) {
addChild(new TokenNode(this.ts)); // lbrack
Exp exp = new Exp(this.ts);
exp.parse(errors);
addChild(exp);
if (getCurrToken().getType() == TokenType.RBRACK) {
addChild(new TokenNode(this.ts)); // rbrack
} else {
errors.addError(new Error(this.ts.peek(-1).getLine(), ErrorType.k));
}
}
}
public int getType() {
if (getChildren().size() == 1) {
TokenNode idenfr = (TokenNode) getChild(0);
Symbol symbol = SymbolManager.getSymbol(idenfr.getName());
if (symbol instanceof ArraySymbol) {
return 1;
}
return 0;
} else {
return 0;
}
}
public int getValue() {
TokenNode idenfr = (TokenNode) getChild(0); //idenfr一定是个常量可在符号表找到且有值
if (getChildren().size() == 1) {
Symbol symbol = SymbolManager.getSymbol(idenfr.getName());
return symbol.getValue(0);
} else {
int index = ((Exp) getChild(2)).getValue();
Symbol symbol = SymbolManager.getSymbol(idenfr.getName());
return symbol.getValue(index);
}
}
}