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

72 lines
2.1 KiB
Java

package frontend.ast.val;
import java.util.ArrayList;
import error.Errors;
import frontend.ast.Node;
import frontend.ast.SyntaxType;
import frontend.lexer.TokenStream;
import frontend.lexer.TokenType;
import frontend.ast.token.TokenNode;
import frontend.ast.exp.Exp;
public class InitVal extends Node {
public InitVal(TokenStream ts) {
super(SyntaxType.INIT_VAL, ts);
}
public void parse(Errors errors) {
if (getCurrToken().getType() == TokenType.LBRACE) {
TokenNode lbrace = new TokenNode(this.ts);
addChild(lbrace);
if (getCurrToken().getType() != TokenType.RBRACE) {
while (true) {
Exp ep = new Exp(this.ts);
ep.parse(errors);
addChild(ep);
if (getCurrToken().getType() == TokenType.COMMA) {
TokenNode comma = new TokenNode(this.ts);
addChild(comma);
} else {
break;
}
}
}
TokenNode rbrace = new TokenNode(this.ts);
addChild(rbrace);
} else {
Exp ep = new Exp(this.ts);
ep.parse(errors);
addChild(ep);
}
}
public ArrayList<Integer> getValue() {
ArrayList<Integer> values = new ArrayList<>();
if (getChild(0) instanceof Exp) {
values.add(((Exp) getChild(0)).getValue());
} else {
for (int i = 1; i < getChildren().size(); i += 2) {
if (getChild(i) instanceof Exp) {
values.add(((Exp) getChild(i)).getValue());
}
}
}
return values;
}
public ArrayList<Exp> getExpList() {
ArrayList<Exp> expList = new ArrayList<>();
if (getChild(0) instanceof Exp) {
expList.add((Exp) getChild(0));
} else {
for (int i = 1; i < getChildren().size(); i += 2) {
if (getChild(i) instanceof Exp) {
expList.add((Exp) getChild(i));
}
}
}
return expList;
}
}